//
//  SGRegisterNextViewController.m
//  HuaMuJinRong
//
//  Created by mac on 16/4/23.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SGRegisterNextViewController.h"
#import "MemberProtocolViewController.h"
#import "SGLoginViewController.h"

@interface SGRegisterNextViewController ()<HTTPClientDelegate> {
    
    NSInteger requestType;
}
@property (weak, nonatomic) IBOutlet SGLoginTextField *phoneCodeTextField;
@property (weak, nonatomic) IBOutlet SGLoginTextField *passwordTextField;
@property (weak, nonatomic) IBOutlet ClickButton *sendPhoneCodeButton;
@property (weak, nonatomic) IBOutlet SGLoginButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *agreementButton;

@property (nonatomic, strong) NetWorkClient *requestClient;

@end

@implementation SGRegisterNextViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    [self initNavBarTitle:@"手机快速注册" andLeftItemName:@"返回" andRightItemName:@""];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self resetNavigationBar];
    if (_requestClient) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initView];
    [self phoneCodeSendRequestData];
}



#pragma mark - Action
- (IBAction)sendPhoneCodeButtonClick:(id)sender {
    [self phoneCodeSendRequestData];
}

- (IBAction)nextButtonClick:(id)sender {
    if (_phoneCodeTextField.text == nil || _phoneCodeTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机验证码！"];
        return;
    }
    [self requestData];
    
}

- (IBAction)agreementButtonClick:(id)sender {
    MemberProtocolViewController *protocolView = [[MemberProtocolViewController alloc] init];
    protocolView.opt = @"8";
    
    [self.navigationController pushViewController:protocolView animated:YES];
}

- (void)textFieldValueChanged {
    
    if (![_phoneCodeTextField.text isEqualToString:@""] && ![_passwordTextField.text isEqualToString:@""]) {
        _nextButton.isActive = YES;
    }else{
        _nextButton.isActive = NO;
    }
}

#pragma mark - Data
- (void)phoneCodeSendRequestData {
    requestType = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"4" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:_phoneNum forKey:@"cellPhone"];
    [parameters setObject:@"2" forKey:@"type"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
        
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)requestData {
    requestType = 2;
    
    NSString *passWord = [NSString encrypt3DES:_passwordTextField.text key:DESkey];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    //注册
    [parameters setObject:@"2" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:_phoneNum forKey:@"mobile"];
    [parameters setObject:passWord forKey:@"pwd"];
    [parameters setObject:_referral forKey:@"referrerName"];
    [parameters setObject:_phoneCodeTextField.text forKey:@"smsCode"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma HTTPClientDelegate
-(void) startRequest {
    
}

-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    NSDictionary *dics=(NSDictionary *)obj;
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        if (requestType == 1) {
            __block NSInteger timeout = DOWNTIME; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
            dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
            dispatch_source_set_event_handler(timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        
                        [_sendPhoneCodeButton setTitle:@"重新获取" forState:UIControlStateNormal];
                        _sendPhoneCodeButton.userInteractionEnabled = YES;
                        [_sendPhoneCodeButton setAlpha:1];
                    });
                }else{
                    NSInteger seconds = timeout % 60;
                    NSString *strTime = [NSString stringWithFormat:@"%.2ld", (long)seconds];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        
                        [_sendPhoneCodeButton setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                        _sendPhoneCodeButton.userInteractionEnabled = NO;
                        [_sendPhoneCodeButton setAlpha:0.4];
                    });
                    timeout--;
                }
            });
            dispatch_resume(timer);
        }else{
            [SVProgressHUD showSuccessWithStatus:@"注册成功！"];
            
            AppDelegateInstance.isFirstLogin = YES;
            AppDelegateInstance.firstLoginNameStr = _phoneNum;
            SGLoginViewController *loginVC = [[SGLoginViewController alloc] init];
            loginVC.backType =  RegisterEnter;
            [self initNavBarTitle:@"" andLeftItemName:@"" andRightItemName:@""];
            [self.navigationController pushViewController:loginVC animated:YES];
}
    }else{
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}

-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error
{
//    [SVProgressHUD showErrorWithStatus:@"连接服务器失败，请稍后再试"];
}

-(void) networkError
{
//    [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
}

#pragma mark - View
- (void)initView {
    _phoneCodeTextField.font = KFontSize(14);
    _passwordTextField.font = KFontSize(14);
    _sendPhoneCodeButton.titleLabel.font = KFontSize(13);
    _agreementButton.titleLabel.font = KFontSize(11);
    _nextButton.titleLabel.font = KFontSize(16);
    
    
    _nextButton.isActive = NO;
    _nextButton.clipsToBounds = YES;
    _nextButton.layer.cornerRadius = kCornerRadius;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_phoneCodeTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_passwordTextField];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
